﻿using System;
using System.IO;
using LitJson;
using viNews.Classes;
using viNews.Controllers;
using visinia.SmartEngine;

public partial class ClientScripts_viNews_Comments_SubmitComment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SaveComment();
    }

    private void SaveComment()
    {
        string json = Request.Params["data"];
        if (string.IsNullOrEmpty(json))
            return;
        CommentData commentdata = JsonMapper.ToObject<CommentData>(json);
        int newsid = 0;
        if (Int32.TryParse(commentdata.newsid, out newsid))
        {
            Comment comment = new Comment();
            comment.NewsId = newsid;
            comment.Author = commentdata.name;
            comment.Website = commentdata.website;
            comment.Email = commentdata.email;
            comment.Content = commentdata.comment;
            comment.Date = DateTime.Now;
            if (BaseController.ModerateComments)
                comment.IsApproved = false;
            else
                comment.IsApproved = true;
            int commentid = CommentController.AddComment(comment);
            if (BaseController.ModerateComments)
            {
                Response.Clear();
                Response.Write("Comment will show up after Moderation");
                Response.End();
            }
            else
            {
                StringWriter writer = new StringWriter();
                Server.Execute(WebRoots.GetModulesRoot + "/viNews/FullView/Comments/RenderComment.aspx?CommentId=" + commentid, writer);
                Response.Clear();
                Response.Write(writer.ToString());
                Response.End();
            }
        }        
    }

    private class CommentData
    {
        private string _newsid;
        public string newsid { get { return _newsid; } set { _newsid = value; } }

        private string _name;
        public string name { get { return _name; } set { _name= value; } }

        private string _website;
        public string website { get { return _website; } set { _website = value; } }

        private string _email;
        public string email { get { return _email; } set { _email = value; } }

        private string _comment;
        public string comment { get { return _comment; } set { _comment = value; } }
    }
}
